<template>
    <div>
        <NoAuthPage v-showNoAuth="'D25-1'" :imgBoxStyle="{ height: '40vh', margin: '0' }" />
        <div v-userAuth="'D25-1'">
            <div style="display: flex;justify-content: space-between;align-items: center;">
                <a-button v-userAuth="'D25-2'" type='primary' @click="handleCreate">
                    <Iconfont class="icon button-icon-style" type="icon-new16f"></Iconfont>
                    {{ $t('创建配额') }}
                </a-button>
                <div style="display: flex;">
                    <div style="width: 120px;margin-top: 4px;">{{ $t('目录路径') }}：</div>
                    <a-input v-model="input" :placeholder="$t('Enter') + $t('目录路径')" />
                    <a-button type='primary' style="margin-left: 8px;" @click="handleSearch">
                        <Iconfont class="icon button-icon-style" type="icon-search16f"></Iconfont>
                        {{ $t('查询') }}
                    </a-button>
                </div>
            </div>

            <a-table style="margin-top:16px" class="bigstyle" rowKey="id" :columns='columns' :loading="loading"
                :dataSource='dataList' :locale="defaultSetting" :pagination='pagination' size='small'
                :scroll="{ x: 1340 }">
                <template slot="state" slot-scope="state">
                    <div v-if="state == '1'">
                        <span class="dot successBg"></span>
                        <span style="margin-left: 8px;">{{ $t('健康') }}</span>
                    </div>
                    <div v-if="state == '2'">
                        <span class="dot failBg"></span>
                        <span style="margin-left: 8px;">{{ $t('异常') }}</span>
                    </div>
                </template>
                <template slot="type" slot-scope="type, record">
                    <span v-if="record.name.length !== 0">{{ typeGroup.get(String(type) + String(record.utype)) }} ({{
            record.name }})</span>
                    <span v-else>{{ typeGroup.get(String(type) + String(record.utype)) }} (-)</span>
                </template>
                <template slot="use_size" slot-scope="use_size, record">
                    <span>{{ formatBytes(use_size) }} / {{ formatBytes(record.reality_max_bytes) }}</span>
                </template>
                <template slot="size_percent" slot-scope="size_percent, record">
                    <div style="display: flex;align-items: center;">
                        <Percent :percent="percent(record.use_size, record.reality_max_bytes)" :color="getProgressColor(percent(record.use_size, record.reality_max_bytes))" />
                        {{ percent(record.use_size, record.reality_max_bytes) }}%
                    </div>
                </template>
                <template slot="use_files" slot-scope="use_files, record">
                    <span>{{ numberFormat(use_files) }} / {{ numberFormat(record.reality_max_files) }}</span>
                </template>
                <template slot="file_percent" slot-scope="file_percent, record">
                    <div style="display: flex;align-items: center;">
                        <Percent :percent="percent(record.use_files, record.reality_max_files)" :color="getProgressColor(percent(record.use_files, record.reality_max_files))"/>
                        {{ percent(record.use_files, record.reality_max_files) }}%
                    </div>
                </template>
                <template slot="operate" slot-scope='text, record'>
                    <div style="display: flex;">
                        <a-tooltip placement='top'>
                            <template slot='title'>
                                <span>{{ $t('Detail') }}</span>
                            </template>
                            <Iconfont class="icon table-operation-icon" type="icon-view16f"
                                @click="handleDetail(record)">
                            </Iconfont>
                        </a-tooltip>
                        <a-tooltip placement='top'>
                            <template slot='title'>
                                <span>{{ $t('Edit') }}</span>
                            </template>
                            <Iconfont v-userAuth="'D25-3'" class="icon table-operation-icon" type="icon-edit16f"
                                @click="handleEdit(record)">
                            </Iconfont>
                        </a-tooltip>
                        <a-tooltip placement='top'>
                            <template slot='title'>
                                <span>{{ $t('Delete') }}</span>
                            </template>
                            <Iconfont v-userAuth="'D25-4'" class="icon table-operation-icon" type="icon-delete16f"
                                @click="handleDelete(record.id, record)">
                            </Iconfont>
                        </a-tooltip>
                    </div>
                </template>
            </a-table>

        </div>
    </div>
</template>

<script>
import EmptyData from '@/components/common/EmptyData'
import NoAuthPage from '@/components/common/NoAuthPage'
import Percent from "./percent";

export default {
    components: { EmptyData, NoAuthPage, Percent },
    data() {
        return {
            loading: false,
            dataList: [],
            defaultSetting: { emptyText: <EmptyData /> },
            pagination: {
                current: 0,
                pageSize: 10,
                total: 0,
                defaultPageSize: 10,
                showTotal: total => `${this.$t('A-total-of')} ${total} ${this.$t('Data')}`,
                showQuickJumper: true,
                showSizeChanger: true,
                pagination: ['5', '10', '20', '25'],
                onShowSizeChange: (page, page_size) => {
                    this.pagination.current = page
                    this.pagination.pageSize = page_size
                    this.getList('', page, page_size)
                },
                onChange: async (page, page_size) => {
                    this.pagination.current = page
                    this.pagination.pageSize = page_size
                    this.getList('', page, page_size)
                },
                buildOptionText: (props) => `${props.value} / ${this.$t('page')}`
            },
            columns: [
                { title: this.$t('目录路径'), dataIndex: 'dir', key: 'dir', width: 160, fixed: 'left', },
                { title: this.$t('配额类型'), dataIndex: 'type', key: 'type', scopedSlots: { customRender: 'type' } },
                { title: this.$t('已用容量/容量配额数'), dataIndex: 'use_size', key: 'use_size', scopedSlots: { customRender: 'use_size' } },
                { title: this.$t('容量使用率'), scopedSlots: { customRender: 'size_percent' } },
                { title: this.$t('已用文件数/文件配额数'), dataIndex: 'use_files', key: 'use_files', scopedSlots: { customRender: 'use_files' } },
                { title: this.$t('文件数使用率'), scopedSlots: { customRender: 'file_percent' } },
                { title: this.$t('Operate'), key: "operate", scopedSlots: { customRender: 'operate' }, width: 160, fixed: 'right' }
            ],
            input: '',
            typeGroup: new Map([
                ['11', '目录'],
                ['21', '本地用户'],
                ['22', 'AD用户'],
                ['31', '本地用户组'],
                ['32', 'AD用户组'],
            ]),
            sambaMap: new Map([]),
            adMap: new Map([]),
            adGroupMap: new Map([]),
        }
    },
    async mounted() {
        await this.getSambaList()
        await this.getADUserList()
        await this.getADGroupList()
        await this.getList()
    },
    methods: {
        getProgressColor(successPercent) {
            let color = ''
            if (successPercent < 80) {
                color = '#006db8'
            } else if (successPercent >= 80) {
                color = '#bc2429'
            }
            return color
        },
        async getSambaList() {
            this.loading = true
            const { data } = await this.$api.samba.getSambaApi()
            const map = new Map([])
            data.samba_user.map((item, index) => {
                map.set(item.id, item.username)
            })
            this.sambaMap = map
            this.loading = false
        },
        async getADUserList() {
            this.loading = true
            const { data } = await this.$api.authentication.getUser({ id: '1' })
            const map = new Map([])
            data.user.map((item, index) => {
                map.set(item.user_id, item.user_name)
            })
            this.adMap = map
            this.loading = false
        },
        async getADGroupList() {
            this.loading = true
            const { data } = await this.$api.authentication.getUserGroup({ id: '1' })
            const map = new Map([])
            data.user.map((item, index) => {
                map.set(item.id, item.department)
            })
            this.adGroupMap = map
            this.loading = false
        },
        async getList(dir_name = '', page = 1, page_size = 10) {
            this.loading = true
            const { data } = await this.$api.directory.getQuotaListApi({
                page,
                page_size,
                dir_name,
            })
            if (data.flag == 1) {
                this.model(data.id) //返回模板
                this.notice(data.id, data.params, data.flag) //通知列表显示
            }
            else {
                data.params.values.map((item, index) => {
                    item.name = []
                    if (item.type == 2 && item.utype == 1) {
                        item.objs.map(subItem => item.name.push(this.sambaMap.get(subItem)))
                    }
                    else if (item.type == 2 && item.utype == 2) {
                        item.objs.map(subItem => item.name.push(this.adMap.get(subItem)))
                    }
                    else if (item.type == 3 && item.utype == 2) {
                        item.objs.map(subItem => item.name.push(this.adGroupMap.get(subItem)))
                    }
                    if (item.name.length !== 0) item.name = item.name.join(',')
                    return item
                })
                this.dataList = data.params.values
                this.pagination.total = data.params.total_size
            }
            this.loading = false
        },
        handleSearch() {
            this.getList(this.input, this.pagination.current, this.pagination.pageSize)
        },
        async handleCreate() {
            localStorage.setItem('fs_current_tab', "FS_Quota");
            this.$router.push({ path: '/createQuota' })
        },
        async handleEdit(item) {
            localStorage.setItem('fs_current_tab', "FS_Quota");
            this.$router.push({
                path: '/modifyQuota',
                query: {
                    item: encodeURIComponent(JSON.stringify(item))
                }
            })
        },
        async handleDelete(id, item) {
            this.loading = true
            let _this = this
            this.$confirm({
                title: this.$t('删除配额'),
                content: this.$t('删除配额名为') + `${item.dir}` + this.$t('后，将无法恢复！您确定要删除吗？'),
                cancelText: this.$t('Cancel'),
                okText: this.$t('Sure'),
                okType: 'danger',
                icon: 'close-circle',
                async onOk() {
                    const { data } = await _this.$api.directory.deleteQuotaListApi({ id })
                    _this.model(data.id) //返回模板
                    _this.notice(data.id, data.params, data.flag) //通知列表显示
                    if (data.flag == '0') {
                        _this.pagination.current = 1
                        _this.pagination.pageSize = 10
                        _this.getList()
                    }
                },
                onCancel() {
                }
            })
            this.loading = false
        },
        handleDetail(item) {
            this.$router.push({
                path: '/quotaDetail',
                query: {
                    item: encodeURIComponent(JSON.stringify(item))
                }
            })
        },
        formatBytes(bytes, decimals = 2) {
            if (bytes === 0 || bytes === null) return '-';
            const k = 1024;
            const dm = decimals < 0 ? 0 : decimals;
            const sizes = ['Bytes', 'KB', 'MB', 'GB', 'TB', 'PB'];
            const i = Math.floor(Math.log(bytes) / Math.log(k));
            return parseFloat((bytes / Math.pow(k, i)).toFixed(dm)) + ' ' + sizes[i];
        },
        numberFormat(value) {
            if (value === 0 || value === null) return '-';
            const param = {};
            let k = 10000,
                sizes = ['个', '万', '亿'],
                i;
            if (value < k) {
                param.value = value;
                param.unit = '个';
            } else {
                i = Math.floor(Math.log(value) / Math.log(k));
                param.value = ((value / Math.pow(k, i)));
                param.unit = sizes[i];
            }
            return param.value + param.unit;
        },
        percent(value1, value2) {
            const result = (value1 / value2 * 100).toFixed(2)
            if (value1 <= 0 || value2 <= 0) return '0.00'
            else if (result > 100) return '100.00'
            else return result
        }
    }
}
</script>

<style scoped>
/* ::v-deep .ant-progress-circle .ant-progress-inner {
    background: #EBEEF0;
} */

/* ::v-deep.ant-table-tbody > tr:hover:not(.ant-table-expanded-row):not(.ant-table-row-selected) > td {
    background: #fff;
} */
</style>
